from django.shortcuts import render,redirect
import pymysql

def classes(request):


    # 创建连接
    conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='t1',charset='utf8')
    # 创建游标
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 执行SQL，并返回收影响行数
    cursor.execute("select id,title from class")


    classlist = cursor.fetchall()

    # 关闭游标
    cursor.close()
    # 关闭连接
    conn.close()
    return render(request,'classes.html',{'class_list':classlist})

def addclass(request):
    if request.method == 'GET':
        return render(request,'addclass.html')

    else:
        # pass
        v = request.POST.get('title')
        print(v)
        # 创建连接
        conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='t1', charset='utf8')
        # 创建游标
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

        # 执行SQL，并返回收影响行数
        cursor.execute("insert into class(title) values(%s) ",(v))

        conn.commit()
        # 关闭游标
        cursor.close()
        # 关闭连接
        conn.close()
        return redirect('/classes/')
